package com.able.concurrency.t1;

import java.util.concurrent.TimeUnit;

/**
 * @author abel.he
 * @data 2018/8/15 19:22
 * @describe 当同步方法中发生异常，自动释放锁资源，不会影响其他线程的执行
 * 注意：同步业务逻辑中，如果发生异常如何处理
 */
public class Test8 {

    private int num = 0;

    synchronized void m1() {
        System.out.println(Thread.currentThread().getName() + "start");
        while (true) {
            num ++;
            System.out.println(Thread.currentThread().getName() + " - " + num);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (num == 5) {
                num = num/0;
            }
        }
    }

    public static void main(String[] args) {
        final Test8 test8 = new Test8();
        new Thread(new Runnable() {
            public void run() {
                test8.m1();
            }
        }, "t1").start();

        new Thread(new Runnable() {
            public void run() {
                test8.m1();
            }
        }, "t2").start();
    }

}
